package org.dashboard.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import org.dashboard.bean.AdRole;
import org.dashboard.bean.AdUser;
import org.dashboard.constant.Constant;
import org.dashboard.service.AdRoleService;
import org.dashboard.service.AdUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * Copyright © 2018. All rights reserved.
 *
 * @Author: FreezeSoul
 * @CreateDate: 2018/8/6 17:16
 * @Description: BaseController
 * @Version: V1.0
 */
public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Reference
    private AdUserService adUserService;

    @Reference
    private AdRoleService adRoleService;


    public String currentUserName(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        if(principal == null) return null;
        return principal.getName();
    }

    public AdUser currentAdUser(HttpServletRequest request){
        String userName = currentUserName(request);
        if(userName == null) return null;
        return adUserService.selectByName(userName);
    }

    public List<AdRole> currentUserAdRoles(HttpServletRequest request){
        AdUser user = currentAdUser(request);
        if(user == null) return null;
        Integer userId = user.getUserId();
        return adRoleService.selectUserAdRoles(userId);
    }

    public boolean currentUserIsManager(HttpServletRequest request){
        List<AdRole> roles = currentUserAdRoles(request);
        return roles.stream().allMatch(s -> s.getRoleType().equals(Constant.ROLE_TYPE_MANAGER));
    }
}
